package haw.its;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Aufgabe 2.1
 */
public class Portscanner {

	/**
	 * Scans ports on host using a Threadpool
	 */
	private static void scan(final String host, int startPort, int endPort) {

		ExecutorService executor = Executors.newCachedThreadPool();
		for (int i = startPort; i <= endPort; i++) {

			final int port = i;

			Runnable run = new Runnable() {
				@Override
				public void run() {
					try {
						Socket s = new Socket();
						s.setSoTimeout(1500);
						SocketAddress adr = new InetSocketAddress(host, port);
						s.connect(adr, 1500);
						System.out.println("Port " + port + " open!");
						s.close();
					} catch (IOException e) {
						// System.out.println("Port " + port + " not open!" + e);
					}
				}
			};
			executor.execute(run);
			
			try {
				//Relax
				Thread.sleep(5);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		executor.shutdown();

		try {
			executor.awaitTermination(60, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param hostadress startPort endPort
	 */
	public static void main(String[] args) {

		System.out.println("Start");
		// scan("www.haw-hamburg.de", 80, 500);
		scan(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2]));
		System.out.println("Ende");
	}

	/**
	 * Ergebnis: 
	 * Start 
	 * Port 80 open! 
	 * Port 443 open! 
	 * Ende
	 */

}
